<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import/index?type=employee')">excel导入</el-button>
          <el-button type="danger" size="small" @click="hanldeDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="openAddDialog">新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="isLoading" style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="indexMethod" width="100px" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{row}">
              <img v-imgError="notFaultImg" :src="row.staffPhoto || defaultImg" class="img-box">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatText" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间">
            <!-- 使用作用域插槽结构获取数据 -->
            <template #default="{row}">
              {{ formateTime(row.timeOfEntry) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="showRoleDialogFn(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page="page"
            :total="total"
            :page-size="size"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" />
      <assignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { delEmployeeApi, getEmployeeListApi } from '@/api/employees'
import EnumObj from '@/constant/employees'
import dayjs from 'dayjs'
import addEmployee from './components/add-employee.vue'
import defaultImg from '@/assets/common/bigUserHeader.png'
import notFaultImg from '@/assets/common/head.jpg'
import assignRole from './components/assign-role.vue'
export default {
  name: 'Employees',
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      page: 1,
      size: 10,
      total: 0,
      list: [],
      isLoading: false,
      showDialog: false,
      // 没有图片地址，展示的默认图
      defaultImg,
      // 有图片地址，但图片地址无法加载的默认图
      notFaultImg,
      // 控制分配权限弹窗的隐藏和显示
      showRoleDialog: false,
      // 单曲点击的用户ID
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    /**
     * 展示分配权限弹窗
     * @param id 点击的用户id
     */
    showRoleDialogFn(id) {
      // console.log(id)
      // 1.打开弹窗
      this.showRoleDialog = true
      // 2.接收到的id传给子组件
      this.userId = id
    },
    /**
     * 导出excel文件
     */
    hanldeDownload() {
      // 导入包方法
      import('@/vendor/Export2Excel').then(async excel => {
        const { data: { rows }} = await getEmployeeListApi(1, this.total)
        const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const list = this.transListToDoubleList(rows, headersArr, headersRelations)
        excel.export_json_to_excel({
          // 表头
          header: headersArr,
          // data 是要导出的数据，并且是一个二维数组
          data: list,
          // 文件名
          filename: '员工信息',
          // 宽度是否自适应
          autoWidth: true,
          // 文件后缀名
          bookType: 'xlsx'
        })
      })
    },
    /**
     * 处理二维数组
     */
    transListToDoubleList(rows, headersArr, headersRelations) {
      const list = []
      rows.forEach(item => {
        const tempArr = []
        headersArr.forEach(headers => {
          const englishKey = headersRelations[headers]
          let value = item[englishKey]
          // 处理聘用形式
          if (englishKey === 'formOfEmployment') {
            const hireType = EnumObj.hireType
            const result = hireType.find(item => item.id === +value)
            value = result ? result.value : '未知'
          }
          // 处理聘用入职日期和转正日期
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = value ? dayjs(value).format('YYYY-MM-DD') : ''
          }
          tempArr.push(value)
        })
        list.push(tempArr)
      })
      return list
    },
    openAddDialog() {
      this.showDialog = true
    },
    /**
     * 删除员工
     * @param id 员工id
     */
    del(id) {
      // console.log(id)
      this.$confirm('您确定要删除该数据吗？', '温馨提示').then(async() => {
        // 放置错误删除 没有传入id
        await delEmployeeApi()
        this.$message.success('删除成功')
        // 判断当前页是否删除的最后一条数据，前往上一页
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.getEmployeeList()
      }).catch(() => {})
    },
    formateTime(time) {
      return time ? dayjs(time).format('YYYY-MM-DD') : ''
    },
    formatText(row, column, callValue, index) {
      // console.log(row, column, callValue, index)
      // 将 callValue 统一转换为 number 类型
      const formOfEmployment = +callValue
      // if (formOfEmployment === 1) {
      //   return '正式'
      // } else if (formOfEmployment === 2) {
      //   return '非正式'
      // }
      const hireType = EnumObj.hireType
      // filter 筛选的结果：数组 或 空数组
      // find 筛选的结果： 符合第条件的第一个元素 或 undefined
      const result = hireType.find(item => item.id === formOfEmployment)
      return result ? result.value : '未知'
    },
    /**
     * 计算序号
     * @param index 序号形参
     */
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeeList()
    },
    /**
     * 获取员工列表
     */
    async getEmployeeList() {
      this.isLoading = true
      const {
        data: { total, rows }
      } = await getEmployeeListApi(this.page, this.size)
      this.total = total
      this.list = rows
      this.isLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.img-box{
  width: 100px;
  height: 100px;
}
</style>
